﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Template10.Services.NavigationService;
using Wasion.HHU.Common;
using Wasion.HHU.Data.Repositories;
using Wasion.HHU.Services;
using Windows.ApplicationModel;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Rfcomm;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking.Sockets;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation.Peers;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using WsProtocol.IEC62056;
using WsProtocol.IEC62056MDL;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Wasion.HHU.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class DataViewDetail : Page
    {
        //public ObservableCollection<Data.Models.Schema> ResultCollection
        //{
        //    get;
        //    private set;
        //}

        //SchemaDbRepository schemaDbRepository = new SchemaDbRepository();

        public DataViewDetail()
        {
            this.InitializeComponent();
            NavigationCacheMode = NavigationCacheMode.Enabled;

            //if (ResultCollection == null)
            //{
            //    ResultCollection = new ObservableCollection<Data.Models.Schema>();
            //}

        }

        

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            //ApplicationData.Current.LocalFolder.CreateFileAsync()
            SaveFileAsync();
        }

        public async Task SaveFileAsync()
        {
            var strA = new List<string>() { "1", "2", "3" };

            Windows.Storage.Pickers.FolderPicker folderPicker = new Windows.Storage.Pickers.FolderPicker();
            folderPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            folderPicker.FileTypeFilter.Add(".");
            StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            //byte[] buffer = new byte[4000];
            try
            {
                var file = await folder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
                //await FileIO.WriteBytesAsync(file, buffer);
                await FileIO.WriteLinesAsync(file, strA);
            }
            catch (Exception ex)
            {
                await new MessageDialog("保存文件失败\n" + ex.Message).ShowAsync();
            }
        }

        /// <summary>
        /// Display a message to the user.
        /// This method may be called from any thread.
        /// </summary>
        /// <param name="strMessage"></param>
        /// <param name="type"></param>
        public void NotifyUser(string strMessage, NotifyType type)
        {
            // If called from the UI thread, then update immediately.
            // Otherwise, schedule a task on the UI thread to perform the update.
            if (Dispatcher.HasThreadAccess)
            {
                UpdateStatus(strMessage, type);
            }
            else
            {
                var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateStatus(strMessage, type));
            }
        }
        private void UpdateStatus(string strMessage, NotifyType type)
        {
            switch (type)
            {
                case NotifyType.StatusMessage:
                    StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
                    break;
                case NotifyType.ErrorMessage:
                    StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
                    break;
            }

            StatusBlock.Text += strMessage;

            // Collapse the StatusBlock if it has no text to conserve real estate.
            StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed;
            if (StatusBlock.Text != String.Empty)
            {
                StatusBorder.Visibility = Visibility.Visible;
                StatusPanel.Visibility = Visibility.Visible;
            }
            else
            {
                StatusBorder.Visibility = Visibility.Collapsed;
                StatusPanel.Visibility = Visibility.Collapsed;
            }

            // Raise an event if necessary to enable a screen reader to announce the status update.
            var peer = FrameworkElementAutomationPeer.FromElement(StatusBlock);
            if (peer != null)
            {
                peer.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
            }
        }

        private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdatePairingButtons();
        }

        private void UpdatePairingButtons()
        {
            
        }

        private void StatusPanel_Tapped(object sender, TappedRoutedEventArgs e)
        {
            StatusPanel.Height = 300;
            StatusScrollViewer.MaxHeight = 300;
            StatusScrollViewer.Height = 300;
            //DisplayNoWifiDialog();
            e.Handled = true;
        }

        private async void DisplayNoWifiDialog()
        {
            ContentDialog noWifiDialog = new ContentDialog()
            {
                Title = "No wifi connection",
                Content = "Check connection and try again.",
                CloseButtonText = "Ok"
            };

            await noWifiDialog.ShowAsync();
        }

        private void Page_Tapped(object sender, TappedRoutedEventArgs e)
        {
            StatusPanel.Height = 50;
            StatusScrollViewer.MaxHeight = 50;
            StatusScrollViewer.Height = 50;
        }

        
    }
}
